package com.yxw.task;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Connection;

import java.sql.Statement;

 

 

public class Database {

    public static void main(String[] args) throws Exception {

        Connection conn = null;

        String sql;

  

        String url = "jdbc:mysql://localhost:3306/test?"

                + "user=root&password=root&useUnicode=true&characterEncoding=UTF8";

 

        try {



            Class.forName("com.mysql.jdbc.Driver");

            // or

            // com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();

            // or

            // new com.mysql.jdbc.Driver();

 

            System.out.println("成功加载MySQL驱动程序");



            conn = DriverManager.getConnection(url);

    

            Statement stmt = conn.createStatement();

            sql = "create table student(NO char(20),name varchar(20),primary key(NO))";

            int result = stmt.executeUpdate(sql);

            if (result != -1) {

                System.out.println("here");

                sql = "insert into student(NO,name) values('2012001','aaa')";

                result = stmt.executeUpdate(sql);

                sql = "insert into student(NO,name) values('2012002','bbb')";

                result = stmt.executeUpdate(sql);

                sql = "select * from student";

                ResultSet rs = stmt.executeQuery(sql);

                System.out.println("学号\t姓名");

                while (rs.next()) {

                    System.out

                            .println(rs.getString(1) + "\t" + rs.getString(2));

                }

            }

        } catch (SQLException e) {

            System.out.println("error");

            e.printStackTrace();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            conn.close();

        }

 

    }

 

}